import React, { useState, useEffect } from "react";
import {
  Table,
  Button,
  Modal,
  Form,
  Input,
  message,
  Space,
  Popconfirm,
  Tag,
} from "antd";
import { reqApplicationList } from "@/api/house";
import AddModel from "./comp/addModel";

const HouseApplication: React.FC = () => {
  const [data, setData] = useState<HouseType[]>([]); //数据源
  const [visible, setVisible] = useState(false); //是否可见
  const [form] = Form.useForm(); //表单里的值
  const [editingKey, setEditingKey] = useState(""); //编辑或是新增
  const [params, setParams] = useState({
    pageNum: 1,
    pageSize: 10,
    condition: {
      username: "",
      isVIP: "",
    },
  }); //请求值
  const [houseInfo, setHouseInfo] = useState<HouseType>({ id: "" }); //用来弹出框回显数据

  const columns = [
    {
      title: "房源名称",
      dataIndex: "houseName",
      key: "houseName",
      editable: "true",
    },
    {
      title: "出租类型",
      dataIndex: "rentType",
      key: "rentType",
      editable: "true",
    },
    {
      title: "房东名称",
      dataIndex: "landlordName",
      key: "landlordName",
      editable: "true",
    },
    {
      title: "联系电话",
      dataIndex: "phone",
      key: "phone",
      editable: "true",
    },
    {
      title: "房屋位置",
      dataIndex: "location",
      key: "location",
      editable: "true",
    },

    {
      title: "房屋状态",
      dataIndex: "state",
      key: "state",
      editable: "true",
      render: (state: number) => {
        if (state === 1) {
          return (
            <Tag bordered={false} color="success">
              房屋在租中
            </Tag>
          );
        } else if (state === 2) {
          return <Tag color="warning">房屋审核中</Tag>;
        } else {
          return <Tag color="error">房屋停租中</Tag>;
        }
      },
    },
    {
      title: "操作",
      key: "action",
      render: (text: string, record: HouseType) => (
        <Space size="middle">
          <Button type="primary" onClick={() => handleEdit(record)}>
            编辑
          </Button>
          <Popconfirm
            title="驳回房源"
            description={`你确定要驳回该房源 ${record.houseName} ?`}
            okText="确定"
            cancelText="取消"
            onConfirm={() => handleDelete(record)}
          >
            <Button type="dashed">驳回</Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  useEffect(() => {
    reqAlist(params);
  }, [params]);
  // const pageChange = (page: number, pageSize: number) => {
  //   setParams({ pageNum: page, pageSize: pageSize });
  // };

  //请求角色列表接口方法
  const reqAlist = async (value: any) => {
    // setLoading(true);
    await reqApplicationList(value).then((res: any) => {
      res.data.list = res.data.list.map((e: any, index: number) => {
        return {
          ...e,
          key: index,
        };
      });
      // setTotal(res.data.total);
      setData(res.data.list);
      // setLoading(false);
    });
  };
  const [inputValue, setInputValue] = useState<string>("");
  const [selectValue, setSelectValue] = useState<string | undefined>(undefined);
  //搜索功能
  const handleSearch = () => {
    reqAlist({
      ...params,
      condition: { username: inputValue, isVIP: selectValue },
    });
  };
  //重置功能
  const handleReset = () => {
    setParams({
      ...params,
      condition: { username: "", isVIP: "" },
    });
    setInputValue("");
  };
  //编辑功能
  const handleEdit = (record: HouseType) => {
    console.log(record);
    setHouseInfo(record);
    form.setFieldsValue(record);
    setEditingKey(record.id);
    setVisible(true);
  };
  //删除功能
  const handleDelete = (record: HouseType) => {
    setData(data.filter((item) => item.id !== record.id));
    message.success("删除成功");
  };

  //弹窗取消
  const handleCancel = () => {
    setHouseInfo({ id: "" });
    setVisible(false);
    reqAlist(params);
  };
  //弹窗完成
  const onFinish = (values: any) => {
    if (editingKey) {
      const index = data.findIndex((item) => item.id === editingKey);
      if (index !== -1) {
        const newData = [...data];
        newData[index] = { ...newData[index], ...values };
        setData(newData);
        setEditingKey("");
        setVisible(false);
        message.success("编辑成功");
      }
    } else {
      const newUser = { key: String(Math.random()), ...values };
      setData([...data, newUser]);
      setVisible(false);
      message.success("添加成功");
    }
  };

  return (
    <div>
      <div
        style={{
          display: "flex",
          justifyContent: "space-between",
          marginBottom: 16,
          padding: "10px 16px 0",
        }}
      >
        <div style={{ display: "flex" }}>
          <Input
            placeholder="输入您需要查找的房源"
            style={{ width: 200, marginRight: "16px" }}
            value={inputValue}
            onChange={(e: React.ChangeEvent<HTMLInputElement>) =>
              setInputValue(e.target.value)
            }
          />
          <Button type="primary" onClick={handleSearch}>
            搜索
          </Button>
          <Button style={{ marginLeft: "8px" }} onClick={handleReset}>
            重置
          </Button>
        </div>
      </div>
      <Table
        columns={columns}
        rowKey={(record) => record.id}
        dataSource={data}
        pagination={{ pageSize: 5 }}
        rowSelection={{
          onChange: (selectedRowKeys, selectedRows) => {
            console.log(selectedRowKeys, selectedRows);
          },
        }}
        bordered
      />
      <AddModel
        open={visible}
        onClose={handleCancel}
        editingKey={editingKey}
        houseInfo={houseInfo}
      ></AddModel>

      {/* <Modal
        title={editingKey ? "编辑用户" : "添加用户"}
        open={visible}
        onCancel={handleCancel}
        footer={null}
      >
        <Form form={form} onFinish={onFinish}>
          <Form.Item
            label="姓名"
            name="name"
            rules={[{ required: true, message: "请输入姓名" }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="年龄"
            name="age"
            rules={[{ required: true, message: "请输入年龄" }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="地址"
            name="address"
            rules={[{ required: true, message: "请输入地址" }]}
          >
            <Input />
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit">
              提交
            </Button>
          </Form.Item>
        </Form>
      </Modal> */}
    </div>
  );
};

export default HouseApplication;
